#!/usr/bin/env python
import MySQLdb

from helpers import get_sorted_tuple

class Recomendations():
    def __init__(self):
        pass
     
    def get_db_con(self):
        con  = MySQLdb.connect(host = 'localhost',
                               user = 'urat',
                               passwd = 'uratpass',
                               db = 'col_filtering')
        
        return con
    
    def get_user_list(self, con, uid):
        cur = con.cursor()
        cur.execute('SELECT item FROM UserLists WHERE uid = %s AND revised = 1', uid)
        return [x for (x,) in cur.fetchall()]
        
    def get_new_user_lists(self, con):
        cur = con.cursor()
        cur.execute('SELECT uid, item FROM UserLists WHERE revised = 0')
        return cur.fetchall()
        
    def mark_revised(self, con, uid, item):
        cur = con.cursor()
        cur.execute('UPDATE UserLists SET revised = 1 WHERE uid = %s AND item = %s' % (uid, item))
        con.commit()

    def get_total_users(self, con, item1, item2):
        cur = con.cursor()
        cur.execute('SELECT total_users FROM UsersForItems WHERE item1 = %s AND item2 = %s', get_sorted_tuple(item1, item2))
        return cur.fetchone()
        
    def update_total_users(self, con, item1, item2, num):
        cur = con.cursor()
        cur.execute('UPDATE UsersForItems SET total_users = ' + str(num) + ' WHERE item1 = %s AND item2 = %s' % get_sorted_tuple(item1, item2))
        con.commit()
    
    def create_total_users(self, con, item1, item2):
        cur = con.cursor()
        cur.execute('INSERT INTO UsersForItems (`item1`, `item2`, `total_users`) VALUES (%s, %s, 1)' % get_sorted_tuple(item1, item2))
        con.commit()
        
    def add_new_feed(self, con, uid, item):
        items = self.get_user_list(con, uid)
        print 'add_new_feed %s %s ...' % (uid, item)
        for it in items:
            total_users = self.get_total_users(con, item, it)
            
            print '%s:%s  = %s' % (item, it, total_users)
            
            if total_users >= (1, ):
                self.update_total_users(con, item, it, total_users[0]+1)
            else:
                self.create_total_users(con, item, it)
    
    
    def process(self):
        con = self.get_db_con()
        
        not_revised = self.get_new_user_lists(con)
        
        for (uid, item) in not_revised:
            self.add_new_feed(con, uid, item)
            
            self.mark_revised(con, uid, item)
